<template>
  <div class="sjplatformSelectForm">
    <el-form :inline="true">
      <el-form-item label="项目名称">
        <el-input v-model="projectTable.queryCondition.projectName" placeholder="请输入名称..." />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="openEditForm('add', null)">新增</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="sjplatformtable">
    <el-table :data="projectTable.tableData" v-loading="loading" empty-text="暂无数据" stripe border style="width: 100%">
      <el-table-column label="序号" width="60">
        <template #default="{ $index }">
          {{ $index + 1 + (currentPage - 1) * pageSize }}
        </template>
      </el-table-column>
      <el-table-column prop="projectName" label="项目名称" class-name="left-align">
        <template #default="{ row }">
          <el-tooltip class="item" effect="light" :content="row.projectName" placement="top">
            <span>{{ row.projectName }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="managerName" label="项目经理" width="100" />
      <el-table-column prop="startTime" label="开始时间" width="140">
        <template #default="{ row }">
          <span>{{ commonUtil.Methods.formatDate(row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="140">
        <template #default="{ row }">
          <span>{{ commonUtil.Methods.formatDate(row.endTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="addTime" label="创建时间" width="140">
        <template #default="{ row }">
          <span>{{ commonUtil.Methods.formatDate(row.addTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="140">
        <template #default="{ row }">
          <div :class="getStatusStyle(row.status)"> {{ getStatusEnumChineseByValue(row.status, ProcessEnum.CreateProject)
            }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-tooltip content="查看详情" placement="bottom" effect="light">
            <i class="detail-icon" @click="showDetail(row.id)"></i>
          </el-tooltip>
          <el-tooltip v-if="row.status == StatusEnum.SubmitApproval" content="撤回审批" placement="bottom" effect="light">
            <i class="revocation-icon" @click="withdrawApproval(row)"></i>
          </el-tooltip>
          <el-tooltip content="提交审批" v-if="row.status == StatusEnum.Creating" placement="bottom" effect="light">
            <i class="submit-icon" @click="submitApprove(row)"></i>
          </el-tooltip>
          <el-tooltip v-if="row.status < StatusEnum.SubmitApproval || row.status == null" content="修改"
            placement="bottom" effect="light">
            <i class="edit-icon" @click="openEditForm('edit', row)"></i>
          </el-tooltip>
          <el-tooltip v-if="row.status < StatusEnum.SubmitApproval || row.status == null" content="删除"
            placement="bottom" effect="light">
            <i class="del-icon" @click="handleDelete(row)"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination layout="prev, pager, next" :total="projectTable.total" :page-size="pageSize"
      :current-page="currentPage" @current-change="handleCurrentChange" />
  </div>
  <el-dialog v-model="newProjectTableVisible" :title="formTitle" width="50%" draggable :destroy-on-close="true">
    <ProjectAddOrUpdate />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="operateProject">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-drawer v-model="isShowDetail" direction="rtl" :before-close="handleDrawerClose">
    <template #header="{ titleId }">
      <h4 :id="titleId">项目详情</h4>
    </template>
    <ProjectDetail :projectId="projectId" />
    <template #footer>
      <el-row>
        <el-col :span="24" class="align-right-buttons">
          <div>
            <el-button type="primary" @click="isShowDetail = false">确定</el-button>
          </div>
        </el-col>
      </el-row>
    </template>
  </el-drawer>
  <el-dialog v-model="newStartFlowVisible" :title="formTitle" width="50%" draggable :destroy-on-close="true">
    <FlowSelect :fid="projectId" :fname="projectName" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelSubmit">取消</el-button>
        <el-button type="primary" @click="confirmSubmitApprove">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import ProjectAddOrUpdate from "./ProjectAddOrUpdate.vue";
import ProjectDetail from "../Common/ProjectDetail.vue";
import FlowSelect from "../../FlowManager/FlowSelect.vue";
import commonUtil from "../../../utils/common";
import { useProjectTable } from "../../../hooks/ProjectManager/Start/useProjectTable";
import { StatusEnum, ProcessEnum, getStatusEnumChineseByValue, getStatusStyle } from "../../../hooks/Common/useStatusEnum";
import { useUploadFileStore } from '../../../store/useUploadFileStore';
import { useApproveTable } from '../../../hooks/ApproveManager/useApproveTable';

let currentPage = ref(1);
let pageSize = ref(10); // 默认每页大小
let formTitle = ref("新增项目");
let loading = ref(false);
let isShowDetail = ref(false);
let projectId = ref('');
let projectName = ref('');

let uploadFileStore = useUploadFileStore();//附件

let newProjectTableVisible = ref(false); //新增机构窗口
let addOrUpdate = ref("add"); //新增还是修改

let newStartFlowVisible = ref(false);//启动流程窗口

let { projectTable, projectStore, queryData, addData, updateData, updateProjectSpecificContent, deleteData } =
  useProjectTable(currentPage, pageSize);
queryData(null);

let { createData, deleteDataByFid } = useApproveTable(currentPage, pageSize);

//查看详情
function showDetail(value) {
  projectId.value = value;
  isShowDetail.value = true;
}

//撤回审批
async function withdrawApproval(project) {
  commonUtil.Methods.confirm("确定撤回审批吗？", async () => {
    projectStore.projectModel.id = project.id;
    projectStore.projectModel.status = StatusEnum.Creating;
    projectStore.projectModel.updateProperties.push('Status');
    if (await deleteDataByFid(project.id) && await updateProjectSpecificContent()) {
      commonUtil.Methods.ShowMessage("success", "撤回审批成功！");
      searchData();
    }
  })
}

//提交审批
function submitApprove(project) {
  formTitle.value = '提交审批';
  projectId.value = project.id;
  projectName.value = project.projectName;
  projectStore.projectModel.id = project.id;
  newStartFlowVisible.value = true;
}
//取消提交审批
function cancelSubmit() {
  newStartFlowVisible.value = false;
}
//确定提交
async function confirmSubmitApprove() {
  if (await createData()) {
    projectStore.projectModel.status = StatusEnum.SubmitApproval;
    if (!projectStore.projectModel.updateProperties) {
      projectStore.projectModel.updateProperties = [];
    }
    projectStore.projectModel.updateProperties.push('Status');
    await updateProjectSpecificContent();
    commonUtil.Methods.ShowMessage("success", "提交审批成功！");
    newStartFlowVisible.value = false;
  }
  searchData();
}

//打开编辑窗口
function openEditForm(value, data) {
  addOrUpdate.value = value;
  if (value == "add") {
    formTitle.value = "新增项目";
    projectStore.resetProjectModel();
  }
  if (value == "edit") {
    formTitle.value = "修改项目";
    projectStore.projectModel = data;
  }
  newProjectTableVisible.value = true;
}

//翻页事件
function handleCurrentChange(newPage) {
  currentPage.value = newPage;
  searchData(); // 根据当前页获取数据
}
//新增或修改
async function operateProject() {
  if (uploadFileStore.hasNotUploadFile) {
    commonUtil.Methods.ShowMessage("warning", "有未上传的附件，请先上传附件后再保存！");
    return;
  }
  //有上传的附件
  if (uploadFileStore.uploadedFileList) {
    if (!projectStore.projectModel.projectDocuments) {
      projectStore.projectModel.projectDocuments = [];
    }
    for (let file of uploadFileStore.uploadedFileList) {
      projectStore.projectModel.projectDocuments.push({ fileName: file.name, docType: 1, objectId: file.objectId, isUsed: 1 });
    }
  }
  projectStore.projectModel.status = StatusEnum.Creating;//项目状态
  if (addOrUpdate.value == "add") {
    if (await addData()) {
      commonUtil.Methods.ShowMessage("success", "新增项目成功！");
      newProjectTableVisible.value = !newProjectTableVisible.value;
    } else {
      commonUtil.Methods.ShowMessage("Oops", "新增项目失败！");
    }
  }
  if (addOrUpdate.value == "edit") {
    if (await updateData()) {
      commonUtil.Methods.ShowMessage("success", "修改项目成功！");
      newProjectTableVisible.value = !newProjectTableVisible.value;
    } else {
      commonUtil.Methods.ShowMessage("Oops", "修改项目失败！");
    }
  }
  searchData();
}
//删除
async function handleDelete(data) {
  if (await deleteData(data.id)) {
    commonUtil.Methods.ShowMessage("success", "删除项目成功！");
  } else {
    commonUtil.Methods.ShowMessage("Oops", "删除项目失败！");
  }
  searchData();
}
//重置按钮
function reset() {
  projectStore.resetProjectModel();
}
//取消新增窗口
function cancel() {
  projectStore.resetProjectModel();
  newProjectTableVisible.value = !newProjectTableVisible.value;
}
//查询按钮
function searchData() {
  loading.value = true;
  currentPage.value = 1;
  queryData(null);
  loading.value = false;
}

function handleDrawerClose() {
  projectId.value = '';
  isShowDetail.value = false;
}
</script>